import React, { Component } from 'react'
import moment from 'moment';

export default class LifeCom extends Component {
  //声明状态 new Date() 
  state = {
    timeStr: moment().format('YYYY-MM-DD HH:mm:ss')
  }
  render() {
    return (
      <div style={{padding: 20, border: 'solid 1px #258', display: 'inline-block'}}>{this.state.timeStr}</div>
    )
  }

  //组件挂载完毕的生命周期钩子 由实例对象自动调用该方法, componentDidMount 只会在组件挂载完成之后执行一次
  componentDidMount(){
    //开启定时器
    this.timer = setInterval(() => {
      console.log('abc');
      //更新状态
      this.setState({
        timeStr: moment().format('YYYY-MM-DD HH:mm:ss')
      })
    }, 1000);
  }

  //componentWillUnmount
  componentWillUnmount(){
    //停止定时器
    clearInterval(this.timer);
  }
}
